# Scenario : recompress FLAC files
# Copyright 2007-2011, Sylvain Rougeaux (Cyber Sinh), www.luminescence-software.org
# Version 2.3 (2011-09-24)

#################################################################
$source = "%SOURCE%\*"
$recursive = %RECURSIVE%
$options = "--no-ogg"
$max_encoding = %MAX_ENCODING%
$priority = "%PRIORITY%"
$shutdown = %SHUTDOWN%
$hibernate = %HIBERNATE%
#################################################################

Clear-Host

$bin = Split-Path $MyInvocation.MyCommand.Definition -Parent

[Reflection.Assembly]::LoadFrom("$bin\Functions.dll") | Out-Null
[Reflection.Assembly]::LoadFrom("$bin\Luminescence.Xiph.dll") | Out-Null

$encoder = "flac"
$flac = "$bin\Encoders\$encoder.exe" 

$version = New-Object -TypeName Version -ArgumentList (&$flac --version).Split(' ')[1]

if ($recursive) { $files = Get-ChildItem $source -Include *.ogg, *.flac -Recurse }
else { $files = Get-ChildItem $source -Include *.ogg, *.flac }

if ($files -eq $null)
{
   Write-Host "There is no file to process."
   exit
}

if ($files.GetType().Name -eq "FileInfo") { $count = 1 }
else { $count = $files.Length }

$i = 0

foreach ($file in $files)
{
   $i++
   Write-Progress -Activity "Updating FLAC files ($i / $count)..." -Status "$file" -PercentComplete ($i / $count * 100)

   if ($file.Extension.ToLowerInvariant() -eq ".ogg")
   {
      $audio = New-Object -TypeName Luminescence.Xiph.OggTagger -ArgumentList $file
      if ($audio.Codec -ne [Luminescence.Xiph.OggCodec]::FLAC) { continue }
   }
   else
   {
      $audio = New-Object -TypeName Luminescence.Xiph.FlacTagger -ArgumentList $file
   }

   $temp_version = New-Object -TypeName Version -ArgumentList $audio.CodecVersion
   if ($version.CompareTo($temp_version) -gt 0)
   {
       $startInfo = New-Object -TypeName Diagnostics.ProcessStartInfo
       $startInfo.FileName = $flac
       $startInfo.Arguments="""$file"" --best --force --silent $options"
       $startInfo.UseShellExecute = $false
       $startInfo.RedirectStandardOutput = $true
       
       $proc = [System.Diagnostics.Process]::Start($startInfo)
       $proc.PriorityClass = $priority

       $nb_instance = (Get-Process | Where-Object { $_.ProcessName -eq $encoder }).Length
       while ($nb_instance -ge $max_encoding)
       {
          Start-Sleep -Milliseconds 500
          $nb_instance = (Get-Process | Where-Object { $_.ProcessName -eq $encoder }).Length
       }
   }
}

Write-Host "Transcoding completes."

if ($shutdown) 
{ 
    shutdown /s /t 3
    exit 
}

if ($hibernate) 
{ 
    shutdown /h /t 3 
    exit
}